package edu.fzu.crud.service;

import com.alibaba.excel.EasyExcel;
import edu.fzu.crud.bean.Student;
import edu.fzu.crud.bean.vo.StuInfoVo;
import edu.fzu.crud.dao.SchoolMapper;
import edu.fzu.crud.dao.StudentMapper;
import edu.fzu.crud.utils.StudentExcelListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author JohnCarraway
 * @create 2020-12-27 20:11
 */
@Service
public class StudentService {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    SchoolMapper schoolMapper;


    /**
     * 查询学生信息带有学校信息
     * @return
     */
    public List<Student> queryAllStudentInfo(){
        List<Student> studentList = studentMapper.queryStudentList(null);
        return studentList;
    }

    public boolean saveStuInfo(HttpServletResponse response, StuInfoVo stuInfoVo) {
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            String date = sdf.format(new Date());
            // 获取当前系统用户名
            String currentSystemUserName = System.getProperty("user.name");
            List<StuInfoVo> list = new ArrayList<>();
            list.add(stuInfoVo);
            // 实现excel的写操作
            // 1.设置写入的文件夹名称和路径
            //C:\Users\Administrator\Desktop
//        String fileName = "C:\\Users\\"+currentSystemUserName+"\\Desktop\\stuExcelTest.xlsx";
            String fileName = "StudentInfo" + date + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            // 2.调用easyexcel中的写入方法
            EasyExcel.write(response.getOutputStream(), StuInfoVo.class).sheet("学生信息").doWrite(list);

        } catch (Exception e){

        }
        return true;
    }

    public void readAndSaveStuInfoFromExcel(MultipartFile file, StudentMapper studentMapper, SchoolMapper schoolMapper) {
        try {
            // 获取文件的输入流
            InputStream inputStream = file.getInputStream();
            // 调用读取文件的方法
            EasyExcel.read(inputStream, StuInfoVo.class, new StudentExcelListener(studentMapper, schoolMapper)).sheet("学生信息").doRead();

        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public boolean exportStuInfoToExcel(List<StuInfoVo> stuInfoVoList) {

        // 实现excel的写操作
        // 1.设置写入的文件夹名称和路径

        String fileName = "D:\\guli_log\\stuExcel.xlsx";
        // 2.调用easyexcel中的写入方法
        EasyExcel.write(fileName, StuInfoVo.class).sheet("学生信息").doWrite(stuInfoVoList);
        return true;
    }
}
